<template>
  <div class="first" style="height： 100vh;">
    <div class="content-box">
      <div class="teaching-box">
        <div class="title">教研信息</div>
        <el-form
          ref="ruleForm"
          :rules="rules"
          class="teaching-form"
          label-width="100px"
          :model="ruleForm"
        >
          <el-form-item label="教研标题：" prop="title">
            <el-col :span="12">
              <el-input v-model="ruleForm.title" placeholder="请输入标题" />
            </el-col>
          </el-form-item>
          <el-form-item label="封面图片：">
            <el-col :span="12">
              <el-upload
                class="avatar-uploader"
                action
                :action="action"
                :header="uploadHeader"
                :data="uploadForm"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
              >
                <div v-if="ruleForm.coverImageUrl">
                  <img :src="ruleForm.coverImageUrl" class="avatar" />
                </div>

                <div v-else>
                  <div
                    class="el-upload__text upload__text"
                    style="font-size:14px; line-height: 160px; color: #666;"
                  >点击上传封面图片</div>
                </div>
              </el-upload>
            </el-col>
          </el-form-item>
        </el-form>
      </div>

      <div class="teaching-box">
        <div class="title clearfix">
          <div class="fl">详细流程</div>
          <el-button class="fr marginT10" type="primary" size="small" @click="next">编辑</el-button>
        </div>
        <el-form ref="file-form" class="teaching-form" label-width="100px" :model="ruleForm">
          <el-form-item
            v-for="(item, index) in ruleForm.stepList"
            :key="index"
            :label="'步骤' + (index + 1)"
            prop="name"
          >
            <el-col :span="12">
              <el-input v-model="item.title" placeholder="点击填写步骤" disabled />

              <div style="display: flex; align-items: center; margin-top: 10px;">
                <el-date-picker
                  v-model="item.startTime"
                  type="datetime"
                  placeholder="开始时间"
                  style="flex: 1;"
                  disabled
                />&nbsp;至&nbsp;
                <el-date-picker
                  v-model="item.endTime"
                  type="datetime"
                  placeholder="结束时间"
                  style="flex: 1;"
                  disabled
                />
              </div>
              <div
                v-for="(activitiesItem, activitiesIndex) in item.activities"
                :key="activitiesIndex"
                class="live-box"
              >
                <div class="step-title">{{ activitiesItem.title }}</div>
                <div class="describe">
                  <div class="left">
                    <span>分类/子分类暂无字段</span>
                    <span>{{ activitiesItem.startTime }}</span>
                  </div>

                  <!-- <div class="right">
                    <span @click="editBtn(activitiesItem, index, activitiesIndex)">编辑</span>
                    <span @click="getDeleteLiveDetail(activitiesItem, index, activitiesIndex)">删除</span>
                  </div>-->
                </div>
              </div>
              <!-- <div class="step-btn">
                <el-button size="mini">添加在线课程</el-button>
                <el-button size="mini">添加在线会议</el-button>
              </div>-->
            </el-col>
          </el-form-item>

          <!-- <el-form-item>
            <el-col :span="12">
              <el-button
                type="primary"
                size="medium"
                plain
                style="width: 100%; margin-top: 20px;"
              >添加步骤</el-button>
            </el-col>
          </el-form-item>-->
        </el-form>
      </div>

      <div class="teaching-box">
        <div class="title">教研介绍</div>
        <el-form ref="teaching-form" class="teaching-form" label-width="100px" :model="ruleForm">
          <el-form-item label prop="name">
            <el-col :span="24">
              <editor v-model="ruleForm.intro" @input="newContent" />
            </el-col>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <div class="matgin30">
        <el-form ref="file-form" class="teaching-form" :model="dialogList">
          <el-form-item prop="title">
            <el-input v-model="dialogList.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item prop="data">
            <div style="display: flex; align-items: center; margin-top: 10px;">
              <el-date-picker
                v-model="dialogList.startTime"
                type="datetime"
                placeholder="开始时间"
                style="flex: 1;"
              />&nbsp;至&nbsp;
              <el-date-picker
                v-model="dialogList.endTime"
                type="datetime"
                placeholder="结束时间"
                style="flex: 1;"
              />
            </div>
          </el-form-item>

          <el-form-item v-if="options.cateTagsList">
            <el-cascader
              v-model="dialogList.cateTagsSelect"
              style="width: 100%;"
              :options="options.cateTagsList"
              :props="{
                multiple: true,
                value: 'tagsId',
                label: 'tagsName',
                children: 'sub',
                checkStrictly: true
              }"
              clearable
              filterable
              placeholder="请选择/输入分类"
              @keyup.enter.native="tabsKeyup($event, 1)"
            />
          </el-form-item>

          <el-form-item v-if="options.colTagsList">
            <el-cascader
              v-model="dialogList.colTagsSelect"
              style="width: 100%;"
              :options="options.colTagsList"
              :props="{
                multiple: true,
                value: 'tagsId',
                label: 'tagsName',
                children: 'sub',
                checkStrictly: true
              }"
              filterable
              clearable
              placeholder="请选择/输入标签"
              @keyup.enter.native="tabsKeyup($event, 2)"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveBtn">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { preUpload } from '@/api/uploads';

import Tinymce from '@/components/Tinymce/index';
import { deleteLiveDetail, updateLive, findColumnTags, findTagsList } from '@/api/activity';
import { reduceArr, assignment, compose } from '@/utils/categoryOrTags';
import { getTimes, timeChange } from '@/utils/time';

export default {
  name: 'First',
  components: {
    editor: Tinymce
  },
  props: ['list'],
  data () {
    return {
      dialogVisible: false,
      dialogTitle: '编辑',
      dialogList: {
        title: '', // 标题
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        cateTagsSelect: '', // 最终分类
        colTagsSelect: '' // 最终标签
      },
      step: {
        firstIndex: '',
        secondIndex: ''
      },
      options: {
        cateTagsList: [], // 分类
        colTagsList: [] // 标签
      },

      action: 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadHeader: {
        'Content-Type': 'multipart/form-data'
      },
      uploadForm: {},

      ruleForm: this.list,
      rules: {
        title: [{ required: true, message: '请输入标题!', trigger: 'blur' }],
        region: [
          { required: true, message: '请选择教研活动!', trigger: 'change' }
        ]
      }
    };
  },
  created () {
    console.log(this.ruleForm);
    this.getSelection();
  },
  methods: {
    // 获取选项
    async getSelection () {
      // 查找栏目分类选项
      // var teachingCode = this.ruleForm.teachingTarget.itemCode;
      // var phaseCode = this.ruleForm.phase.itemCode;
      // var subjectCode = this.ruleForm.subject.itemCode;
      // var columnObj = {
      //   growthClassify: teachingCode || null,
      //   stageList: [phaseCode] || null,
      //   subjectList: [subjectCode] || null
      // };
      await findColumnTags({}).then(res => {
        this.options.cateTagsList = res.data;
        var cateTagsSelect = [];
        if (this.checkArr(this.ruleForm.cateTags)) {
          this.ruleForm.cateTags.map(item => {
            var items = this.options.cateTagsList.filter(data => data.tagsId === item.tagsId);
            if (this.checkArr(items)) {
              cateTagsSelect.push(items[0].tagsId);
            }
          });
        }
        this.ruleForm.cateTagsSelect = cateTagsSelect;
      });

      // var tagsObj = {
      //   growthClassify: teachingCode || null,
      //   stageId: phaseCode || null,
      //   subjectId: subjectCode || null,
      //   tagsKindEnum: 'TEACHINGRESEARCH',
      //   tagsTypeEnum: 'CATEGORY_TAGS'
      // };
      // 查询标签选项
      await findTagsList({
        tagsKindEnum: 'TEACHINGRESEARCH',
        tagsTypeEnum: 'CATEGORY_TAGS'
      }).then(res => {
        this.options.colTagsList = res.data;
        var colTagsSelect = [];
        if (this.checkArr(this.ruleForm.colTags)) {
          this.ruleForm.colTags.map(item => {
            var items = this.options.colTagsList.filter(data => data.tagsId === item.tagsId);
            if (this.checkArr(items)) {
              colTagsSelect.push(items[0].tagsId);
            }
          });
        }
        this.ruleForm.colTagsSelect = colTagsSelect;

        console.log('123this.ruleForm:', this.ruleForm);
      });
    },

    // 添加选项
    tabsKeyup (e, index) {
      var obj;
      switch (index) {
        case 1: // 分类
          obj = {
            tagsId: this.options.cateTagsList.length + '',
            tagsName: e.target.value,
            children: []
          };
          this.options.cateTagsList.push(obj);
          break;
        case 2: // 标签
          obj = {
            tagsId: this.options.colTagsList.length + '',
            tagsName: e.target.value
          };
          this.options.colTagsList.push(obj);
          break;
      }
    },

    // 删除步骤在线课程
    getDeleteLiveDetail (item, firstIndex, secondIndex) {
      this.step.firstIndex = firstIndex;
      this.step.secondIndex = secondIndex;

      const msg = '确认是否删除该步骤！';
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.ruleForm.stepList[firstIndex].activities.splice(secondIndex, 1);
        })
        .catch(() => {
          // 取消操作
          console.log('cancel');
        });
    },
    // 编辑步骤在线课程
    editBtn (item, firstIndex, secondIndex) {
      this.step.firstIndex = firstIndex;
      this.step.secondIndex = secondIndex;
      switch (item.type) {
        case 'TEACHING_RESEARCH':
          this.dialogTitle = '编辑教研';
          break;
        case 'LIVE_BORADCAST':
          this.dialogTitle = '编辑在线课程';
          break;
        case 'MEETING':
          this.dialogTitle = '编辑会议';
          break;
        case 'PREPARE_LESSON':
          this.dialogTitle = '编辑教学设计';
          break;
      }

      if (item.progress !== 'NOT_STARTED') {
        this.$message.error('活动开始之后不允许修改!');
      } else {
        var cateTagsSelect = [];
        this.ruleForm.stepList[firstIndex].activities[secondIndex].cateTags.map(item => {
          var items = this.options.cateTagsList.filter(data => data.tagsId === item.tagsId);
          if (items.length > 0) {
            cateTagsSelect.push(items[0].tagsId);
          }
        });

        var colTagsSelect = [];
        this.ruleForm.stepList[firstIndex].activities[secondIndex].colTags.map(item => {
          var items = this.options.colTagsList.filter(data => data.tagsId === item.tagsId);
          if (items.length > 0) {
            colTagsSelect.push(items[0].tagsId);
          }
        });

        this.dialogList = {
          title: item.title ? item.title : '',
          startTime: item.startTime ? item.startTime : '',
          progress: item.progress ? item.progress : '',
          endTime: item.startTime ? item.startTime : '',
          cateTagsSelect: cateTagsSelect || '',
          colTagsSelect: colTagsSelect || ''
        };
        this.dialogVisible = true;
      }
    },

    // 保存步骤在线课程
    saveBtn () {
      var startTime = new Date(this.dialogList.startTime).getTime();
      this.dialogList.startTime = getTimes(startTime);
      var endTime = new Date(this.dialogList.endTime).getTime();
      this.dialogList.endTime = getTimes(endTime);

      var firstIndex = this.step.firstIndex;
      var secondIndex = this.step.secondIndex;
      // 分类
      if (this.dialogList.cateTagsSelect) {
        this.options.cateTagsList = assignment(this.options.cateTagsList);
        var arr = compose(this.dialogList.cateTagsSelect, this.options.cateTagsList); // 组合接口数据 - 分类
        this.ruleForm.stepList[firstIndex].activities[secondIndex].cateTagsSelect = this.dialogList.cateTagsSelect;
        this.ruleForm.stepList[firstIndex].activities[secondIndex].cateTags = arr;
      }

      // 标签
      if (this.dialogList.colTagsSelect) {
        this.options.colTagsList = assignment(this.options.colTagsList);
        var arr = compose(this.dialogList.colTagsSelect, this.options.colTagsList); // 组合接口数据 - 标签
        this.ruleForm.stepList[firstIndex].activities[secondIndex].colTagsSelect = this.dialogList.colTagsSelect;
        this.ruleForm.stepList[firstIndex].activities[secondIndex].colTags = arr;
      }
      this.dialogVisible = false;
    },

    uploadSuccess (res, file) {
      this.ruleForm.coverImageUrl = this.coverImageUrl;
      console.log('this.ruleForm:', this.ruleForm);
    },
    beforeUpload (file) {
      const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;
      if (!imgStr.test(file.name)) {
        this.$message.error('上传格式不对，请重新上传!');
        return false;
      }
      let continueUpload = false;
      return new Promise((resolve, reject) => {
        preUpload({
          biz: 'OPEN',
          name: file.name,
          size: file.size
        }).then(res => {
          this.action = res.data.action;
          this.uploadForm = res.data.parameters;
          this.coverImageUrl = res.data.uri;

          continueUpload = true;
          resolve(continueUpload);
        }).catch(err => {
          reject(continueUpload);
        });
      });
    },

    // 弹窗关闭按钮
    handleClose (done) {
      console.log(12312312312);
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },

    newContent (val) {
      this.ruleForm.intro = val;
    },
    handleAvatarSuccess (res, file) {
      console.log('上传成功后');
      this.form.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload (file) {
      console.log('上传之前');
      console.log(file);

      var imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;

      if (!imgStr.test(file.name)) {
        this.$message.error('上传格式不对，请重新上传!');
        return;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
    },

    // 下一步
    next () {
      this.ruleForm.step = 'second';
      this.$emit('Callback', this.ruleForm);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.avatar-uploader {
  display: inline-block;
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  .icon-text {
    width: 200px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.step {
  .step-title {
  }
  span {
    margin: 0 8px;
  }
  .el-input {
    width: 90% !important;
  }
  .step-btn {
    margin-left: 20px;
    margin-top: 10px;
  }
}

.first {
  .content-box {
    padding: 0 40px;
    padding-bottom: 0;
    background: rgba(245, 246, 250, 1);
    overflow: hidden;

    .teaching-box {
      margin-top: 24px;
      background-color: white;
      padding-bottom: 16px;
      border-radius: 16px;
      .title {
        border-bottom: 1px solid #d9d9d9;
        line-height: 46px;
        padding: 0 40px;
        font-size: 16px;
        font-family: MicrosoftYaHei;
        color: rgba(0, 0, 0, 0.85);
      }

      .teaching-form {
        margin-top: 40px;
        padding: 0 40px;
      }
      .textarea {
        padding: 20px;
        line-height: 24px;
        background: rgba(0, 0, 0, 0.02);
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
      }

      .live-box {
        background-color: #f5f6fa;
        border-radius: 10px;
        margin: 10px 0;
        padding: 10px;
        .step-title {
          line-height: 24px;
        }
        .describe {
          line-height: 24px;
          color: #999;
          display: flex;
          justify-content: space-between;
          .right {
            span {
              cursor: pointer;
            }
            span:not(:first-child) {
              margin-left: 8px;
            }
            span:nth-child(1) {
              color: #1e87f0;
            }
            span:nth-child(2) {
              color: red;
            }
          }
        }
      }
    }

    .button-box {
      margin-top: 24px;
      .submit {
        width: 128px;
        height: 40px;
        border: none;
        background: rgba(84, 184, 123, 1);
        border-radius: 4px;

        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
        line-height: 24px;
        cursor: pointer;
      }
    }
  }
}
</style>
